package com.cloudeasy.smtp.listener;

import com.cloudeasy.api.constant.AmqpConstant;
import com.cloudeasy.api.util.JsonUtil;
import com.cloudeasy.api.vo.amqp.AuthCodeVO;
import com.cloudeasy.smtp.properties.SmtpProperties;
import com.cloudeasy.smtp.util.SmtpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;


@Component
@Slf4j
public class SmtpListener {

    private final JavaMailSender javaMailSender;

    private final SmtpProperties smtpProperties;

    public SmtpListener(JavaMailSender javaMailSender, SmtpProperties smtpProperties) {
        this.javaMailSender = javaMailSender;
        this.smtpProperties = smtpProperties;
    }

    @RabbitListener(queuesToDeclare = @Queue(AmqpConstant.SmtpConstant.ROUTING_KEY))
    public void process(String message) {
        AuthCodeVO authCodeVO = JsonUtil.fromJson(message, AuthCodeVO.class);
        if (authCodeVO == null) {
            return;
        }
        log.info("recipient = {}", authCodeVO.getRecipient());
        log.info("authCode = {}", authCodeVO.getAuthCode());
        try {
            javaMailSender.send(SmtpUtil.buildAuthCode(javaMailSender, smtpProperties, authCodeVO));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
